﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
using System.Linq;

namespace Dracham.MapEditor.Textures
{
    public class Texture
    {
        public String Name { get; set; }
        public Image Image { get; set; }
        public List<Tile> Tiles { get; set; }

        public Texture(String name, Byte[] imageBytes, Boolean useTransparency, Int32 argb) : this(name, imageBytes, useTransparency, Color.FromArgb(argb)) { }
        public Texture(String name, Byte[] imageBytes, Boolean useTransparency, Color color)
        {
            this.Name = name;

            if (imageBytes != null && imageBytes.Length > 0)
            {
                MemoryStream ms = new MemoryStream();
                ms.Write(imageBytes, 0, imageBytes.Length);
                ms.Seek(0, SeekOrigin.Begin);

                Image = Bitmap.FromStream(ms);
            }

            this.LoadTiles(useTransparency, color);
        }

        public Tile GetTile(Int32 x, Int32 y)
        {
            return Tiles.Where(t => t.X == x && t.Y == y).SingleOrDefault();
        }

        private void LoadTiles(Boolean useTransparency, Color color)
        {
            this.Tiles = new List<Tile>();

            if (this.Image != null)
            {
                Int32 tw = this.Image.Width / 32;
                Int32 th = this.Image.Height / 32;
                Bitmap bm;
                Graphics g;

                for (Int32 x = 0; x < tw; x++)
                {
                    for (Int32 y = 0; y < th; y++)
                    {
                        bm = new Bitmap(32, 32);
                        g = Graphics.FromImage(bm);
                        g.DrawImage(this.Image, new Rectangle(0, 0, 32, 32), new Rectangle(x * 32, y * 32, 32, 32), GraphicsUnit.Pixel);
                        if (useTransparency)
                        {
                            bm.MakeTransparent(color);
                        }

                        Tiles.Add(new Tile((Image)bm, x, y, this));
                    }
                }
            }
        }

        public override string ToString()
        {
            return this.Name;
        }
    }
}
